import 'dart:async';

import 'package:flutter/material.dart';
import 'package:xvideos/hj_model/splash/domain_source_model.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/routers/jump_router.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';
import 'package:provider/provider.dart';

final limitTimeProvider = LimitTimeEventProvider();

//限时活动
class LimitTimeEventProvider extends ChangeNotifier {
  static final LimitTimeEventProvider _instance = LimitTimeEventProvider._();
  LimitTimeEventProvider._();
  factory LimitTimeEventProvider() => _instance;
  Timer? _timer;
  BannerJump? bannerJump; //限时Banner活动
  String deadline = ''; // 限时活动时间倒计时

  //是否展示显示活动 后台返回bannerjump && 结束时间未到
  bool showLimitEvent() => bannerJump != null && calculateDiffToEnd() > 0;

  /// 截止时间的差值
  int calculateDiffToEnd() {
    return bannerJump?.additionalProp?.endAt?.calculateDiffDateByAfterDate() ?? -1;
  }

  //是否开启限时活动
  handleLimitTimeEvent() {
    if (showLimitEvent()) {
      if (_timer == null) {
        _startTimer();
      }
    }
    notifyListeners();
  }

  // 定时器
  _startTimer() {
    Timer.periodic(Duration(seconds: 1), (timer) {
      deadline = bannerJump?.additionalProp?.endAt?.formartPaybalanceByDate() ?? '';
      if (calculateDiffToEnd() < 0) {
        timer.cancel();
        _timer = null;
      }
      notifyListeners();
    });
  }

  limitBannerDetailView() {
    return InkWell(
      onTap: () => pushToPageByLink(bannerJump?.additionalProp?.url),
      child: Container(
        height: 36,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned.fill(
              child: NetworkImageLoader(
                imageUrl: bannerJump?.additionalProp?.banner ?? '',
                borderRadius: 0,
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              right: 12,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 18, vertical: 3),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(99),
                  color: Colors.black.withOpacity(0.2)
                ),
                child: Consumer<LimitTimeEventProvider>(
                  builder: (context, value, child) => Text(
                    '${value.deadline} ',
                    style: textStyle(12, Colors.white, FontWeight.w400),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
